package com.atguigu;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class SharedResource {

    private final Queue<Integer> queue;
    private final int capacity;
    private final ReentrantLock lock;
    private final Condition notFull;
    private final Condition notEmpty;

    public SharedResource(int capacity) {
        this.queue = new LinkedList<>();
        this.capacity = capacity;
        this.lock = new ReentrantLock();
        this.notFull = lock.newCondition();
        this.notEmpty = lock.newCondition();
    }

    public void produce(int value) throws InterruptedException {
        lock.lock();
        try {
            // 如果队列已满，等待
            while (queue.size() == capacity) {
                notFull.await();
            }
            queue.offer(value);
            System.out.println("Produced: " + value);
            notEmpty.signal(); // 唤醒等待的消费者
        } finally {
            lock.unlock();
        }
    }

    public int consume() throws InterruptedException {
        lock.lock();
        try {
            // 如果队列为空，等待
            while (queue.isEmpty()) {
                notEmpty.await();
            }
            int value = queue.poll();
            System.out.println("Consumed: " + value);
            notFull.signal(); // 唤醒等待的生产者
            return value;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        SharedResource resource = new SharedResource(5);
        Thread producerThread = new Thread(new Producer(resource));
        Thread consumerThread = new Thread(new Consumer(resource));

        producerThread.start();
        consumerThread.start();

    }
}
